﻿using System;
using System.Collections.Generic;
using Firefly.Framework.ContentManagement;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

namespace Firefly.Framework.Windows
{
    public class ThemePart : IPipelineSerializeable, IHasContent, IDisposableEx
    {
        [ContentSerializerIgnore]
        protected Texture2D Texture { get; set; }
        public string AssetName { get; set; }
        public Point MinimumSize { get; set; }
        public Dictionary<string, Rectangle> Rectangles { get; set; }
        [ContentSerializer(Optional = true)]
        public Vector4 ClientAreaOffset { get; set; }
        [ContentSerializer(Optional = true)]
        public Vector4 TextOffset { get; set; }

        public ThemePart()
        {
            MinimumSize = Point.Zero;
            Rectangles = new Dictionary<string, Rectangle>();
        }

        public virtual void Draw(string style, Rectangle dest, Color color)
        {
            if (Rectangles.ContainsKey(style))
            { 
                WindowsService.Instance.SpriteBatch.Draw(Texture, dest, Rectangles[style], color); 
            }
            else
            { 
                WindowsService.Instance.SpriteBatch.Draw(Texture, dest, null, color); 
            }
        }

        #region IPipelineSerializeable Members

        public virtual void DeserializeContent(ContentReader input)
        {
            AssetName = input.ReadString();
            Rectangles = input.ReadObject<Dictionary<string, Rectangle>>();
            ClientAreaOffset = input.ReadObject<Vector4>();
            TextOffset = input.ReadObject<Vector4>();
            MinimumSize = input.ReadObject<Point>();
            LoadContent();
        }

        #endregion

        #region IHasContent Members

        public virtual void LoadContent()
        {
            Texture = ContentService.Instance.Load<Texture2D>(WindowsService.Instance.ThemePath + AssetName);
        }

        public virtual void UnloadContent()
        {
            ContentService.Instance.Release(WindowsService.Instance.ThemePath + AssetName);
        }

        #endregion

        #region IDisposableEx Members

        public bool Disposed { get; private set; }

        #endregion

        #region IDisposable Members

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected void Dispose(bool disposing)
        {
            if (!Disposed)
            {
                if (disposing)
                {
                    UnloadContent();
                }

                Disposed = true;
            }
        }

        ~ThemePart()
        {
            Dispose(false);
        }

        #endregion
    }
}
